Skip to content

Fix/postgres password and review fixes v4#35

Merged
sheepdestroyer merged 31 commits into
masterfrom
fix/postgres-password-and-review-fixes-v4
Jun 20, 2026
Merged

Fix/postgres password and review fixes v4#35
sheepdestroyer merged 31 commits into
masterfrom
fix/postgres-password-and-review-fixes-v4

Conversation

@sheepdestroyer

Copy link
Copy Markdown
Owner

Overview

This PR implements robust router-side cooldown management for Ollama backends, integrates Valkey/Redis state synchronization for circuit breakers and cooldowns, fixes postgres database credentials handling, resolves several security/session fingerprinting issues, and upgrades the fallback cascade logic. It also updates documentation and includes a comprehensive verification script suite.

Detailed Changes

1. Ollama Cooldown Gating & Triage Routing

  • Implements router-side Ollama cooldown enforcement. When an Ollama model fails, the router triggers a cooldown (defaulting to 300 seconds, configurable via OLLAMA_COOLDOWN_SECONDS environment variable) and skips Ollama on subsequent requests (falling back to OpenRouter or returning a 429).
  • Added sync_cooldowns_from_valkey and save_cooldowns_to_valkey to persist the cooldown and circuit breaker states across router instances via a Valkey cache.

2. Circuit Breaker Hardening

  • Split the circuit breaker into Google (Gemini) and Vendor (Claude/GPT) breakers to manage independent 5-hour quota refresh cycles.
  • Hardened status checking by using non-mutating checks (is_currently_allowed()) for Prometheus/Metrics polling to prevent consuming the single probe request.
  • Deferred probe consumption until immediately before executing a specific tier in agy_proxy.py.

3. Session & Token Safety

  • Removed content-based session ID hashing/fingerprinting. The session ID is now extracted strictly from explicit session fields (body.get("session_id"), body.get("session"), or request.headers.get("x-session-id")) to prevent cross-conversation collision.
  • Hardened token limit pre-screening by raising a 400 Bad Request error if the safe maximum tokens falls below 1024.
  • Added type validation on tool_calls in message classification to prevent TypeErrors on malformed payloads.

4. Spend Tracking and UI Log Support

  • Patched LiteLLM's spend_management_endpoints.py at runtime to support a wider array of date/time formats in the Admin UI.
  • Corrected timezone parsing in _parse_detail_date to use .astimezone() rather than overriding the tzinfo of timezone-aware datetimes.

5. Deployment manifests & start script

  • Switched postgres password and DATABASE_URL to be dynamically resolved from environment variables instead of being hardcoded.
  • Updated pod.yaml port quotes to satisfy Dependabot parsing.
  • Centralized key loading and metrics query helpers, and wrapped temp file operations in try...finally blocks for cleanups.

LiteLLM Community Edition's deployment cooldown is unreliable for
single-deployment model groups and fallback-target groups. The previous
approach (multi-deployment replicas, allowed_fails_policy) did not
reliably cool down llm-routing-ollama, causing crashloops when Ollama
was rate-limited.

New approach: the triage router manages Ollama cooldowns internally.
When Ollama fails (429/502/503), the router activates a 5-minute
cooldown (configurable via OLLAMA_COOLDOWN_SECONDS env var). During
cooldown, all Ollama requests are immediately rejected:
- Auto modes: silently fall back to the free tier
- Direct/fallback mode: return 429 so LiteLLM skips to openrouter-auto

Changes:
- router/main.py: Add _ollama_cooldown_until state, cooldown check
  before Ollama proxy call, and activation on failure. Add Prometheus
  metrics (ollama_cooldown_active, ollama_cooldown_remaining_seconds).
- litellm/config.yaml: Remove test-fallback-model, remove duplicate
  llm-routing-ollama deployment (127.0.0.2), restore Ollama api_base
  to production (api.ollama.com), remove enterprise-only
  allowed_fails_policy.
- README.md: Update sequence diagrams, Fallback and Cooldown Behavior
  section, and metrics table to document router-side cooldown.
…ing in sed, expected model asserts in tests, synced metrics documentation
…fecycles, and handle transient exception status codes
… breaker Valkey calls, generic error detail messages, SSE stream token counting, secure YAML rendering, and robust verification script exit codes
- Decouple agy_proxy from main by introducing CooldownPersistence protocol and passing client/cooldown_persistence parameters.
- Manage http client lifetime cleanly in agy_proxy.
- Reset Valkey client state and cache last init attempt on exceptions to enforce the 5s retry cooldown.
- Add isinstance(msg, dict) guards to prevent crashes on malformed payloads.
- Use incremental UTF-8 decoder in stream generator to prevent character corruption.
- Remove dead should_close_client variables and conditions.
- Guard test_antigravity_connection when agentapi is missing.
- Fix typo in README.
… Table

- ci: add httpx to test workflow pip install for test_a2_verify.py

- config: add public_model_groups list to litellm_settings so all agent-*,
  openrouter-auto, llm-routing-ollama, and ollama-deepseek-* groups appear
  in the LiteLLM Model Hub Table UI

- config: add full model_info to all model_list entries (supports_vision,
  supports_reasoning, supports_function_calling, mode, max_tokens,
  max_input_tokens, is_public_model_group)

- config: set llm-routing-ollama and ollama-deepseek-v4-{pro,flash} context
  windows to 512K (524288 tokens), up from 131K/262K

- config: add DeepSeek API equivalent per-token costs to ollama models for
  Langfuse cost tracking:
    ollama-deepseek-v4-pro:   $1.74/1M input, $3.48/1M output
    ollama-deepseek-v4-flash: $0.14/1M input, $0.28/1M output

- router: enrich /model/new roster sync payload with model_info (features,
  context length from OpenRouter API, is_public_model_group) for all
  dynamically registered agent-* tiers

- router: add _register_ollama_models_in_db() — registers ollama-deepseek
  models via /model/new at startup so their model_info wins over LiteLLM's
  internal ollama_chat provider lookup (which returns null/false for unknown
  models in /model_group/info aggregation)
…t capabilities, align returned context lengths, and refactor verify scripts to httpx)
…_status in metrics fetch, detailed HTTP routing diagnostics, and defensive config type checking)

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @sheepdestroyer, your pull request is larger than the review limit of 150000 diff characters

@coderabbitai

coderabbitai Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@sheepdestroyer, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 56 minutes and 3 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 95e3a5cd-10a8-4a62-b668-f4895463f7d8

📥 Commits

Reviewing files that changed from the base of the PR and between 3b2a8c7 and 616eb00.

📒 Files selected for processing (28)
  • .github/dependabot.yml
  • .github/workflows/test.yml
  • README.md
  • hello.py
  • litellm/config.yaml
  • litellm/entrypoint.py
  • pod.yaml
  • router/Dockerfile
  • router/agy_proxy.py
  • router/circuit_breaker.py
  • router/free_models_roster.json
  • router/main.py
  • scripts/README.md
  • scripts/backup.sh
  • scripts/extract_gapfill.py
  • scripts/extract_prompts.py
  • scripts/reclassify_all.py
  • scripts/retry_errors.py
  • scripts/verification/mock_rate_limit_server.py
  • scripts/verification/verification_helpers.py
  • scripts/verification/verify_direct_ollama_cooldown.py
  • scripts/verification/verify_ollama_cooldown.py
  • scripts/verification/verify_ollama_routing.py
  • start-stack.sh
  • sync_gemini_token.py
  • test_antigravity.py
  • test_classifier_accuracy.py
  • test_goose.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/postgres-password-and-review-fixes-v4

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements an internal, router-side cooldown mechanism for Ollama backends to prevent cascading fallback loops, using Valkey/Redis to persist and sync cooldown and circuit breaker states. It refactors the triage router to utilize a shared HTTP client, estimate prompt tokens, clamp maximum tokens to fit downstream context windows, and register static Ollama models in the LiteLLM database to ensure model capabilities are correctly reported. Additionally, it removes hardcoded system paths across deployment scripts and test suites, introduces dynamic placeholder rendering for pod.yaml, and adds comprehensive verification scripts and documentation. As there are no review comments, I have no feedback to provide on the review itself.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@sheepdestroyer
sheepdestroyer merged commit 20ed202 into master Jun 20, 2026
6 checks passed
@sheepdestroyer
sheepdestroyer deleted the fix/postgres-password-and-review-fixes-v4 branch June 20, 2026 21:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant